import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import { PROJECT_TASK_STATUS } from '@/consts/project'
import { Button, Table, Tag, Badge } from 'antd'
import { useState, useEffect } from 'react'
import styles from './styles.less'
import { connect, history } from 'umi';
import UserBrief from '@/components/UserBrief'
import { formetDate, formetTime_MDHm } from '@/utils/dateUtils'
import CheckActon from '../../CheckActoin'
import ActionDropdown from '@/components/ActionDropdown';
import TaskAddModal from './../TaskAddModal'
import { pageTask } from '@/services/project/task'
import { TASK_TYPE } from '@/consts/project'
import { TaskRelItemTypeSelect } from "../TaskDetail"

export const TaskStatus = (props) => {
    const {
        status
    } = props

    if (status || status === 0) {
        return <Tag color={PROJECT_TASK_STATUS[status].color}>{PROJECT_TASK_STATUS[status].name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}


const TaskPage = (props) => {
    const {
        projectId,
        showItemColumn = true,
        queryInitParams = {},
        onQueryParamChange,
        projectPermission,
    } = props

    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 10
    })
    const [showAddTaskModalVisiable, setShowAddTaskModalVisiable] = useState(false)
    const [showMe, setShowMe] = useState(false)
    const [taskPage, setTaskPage] = useState();
    const [taskPageLoading, setTaskPageLoading] = useState(false);
    const [permission, setPermission] = useState({})

    useEffect(() => {
        const initParam = {
            ...params,
            ...queryInitParams
        }
        setParams(initParam)
        if (projectId) {
            queryTaskPage(initParam)
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.task
        })
    }, [projectPermission])

    const onParamChange = (param, doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        if (onQueryParamChange) {
            onQueryParamChange(newParams)
        }
        if (doQuery) {
            queryTaskPage(newParams)
        }
    }

    const queryTaskPage = (queryParams) => {
        setTaskPageLoading(true)
        pageTask(projectId, (queryParams || params)).then(({ data }) => {
            setTaskPage(data)
            setTaskPageLoading(false)
        })
    }

    const showTaskDetail = (prod) => {
        history.push(`/projects/${projectId}/task/${prod.id}`)
    }

    const saveTask = () => {
        queryTaskPage();
        setShowAddTaskModalVisiable(false);
    }

    const queryItems = [

        {
            name: "inStatus",
            label: "状态",
            isMain: true,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(PROJECT_TASK_STATUS).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "likeName",
            label: "名称",
            isMain: false,
            span: 8,
            type: "input",
        },
        {
            name: "inUserId",
            label: "负责人",
            isMain: false,
            span: 8,
            type: "userSelect",
        },
        {
            name: "projectItem",
            label: "所属项目",
            isMain: false,
            span: 8,
            type: "custom",
            render: () => {
                return <TaskRelItemTypeSelect
                    projectId={projectId}
                    allowClear={true}
                    width="100%"
                    defaultItemType={params.projectItemType || "PROD"}
                    defaultItemId={params.projectItemId}
                    onChange={(data) => {
                        onParamChange({
                            projectItemId: data.projectItemId,
                            projectItemType: data.projectItemType
                        }, true)
                    }}
                ></TaskRelItemTypeSelect>
            }
        }
    ]

    const actionHeader = [
        <ActionDropdown
            status={params?.isArchived && "filter"}
            key="actions"
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />
        ,
        permission.add &&
        <Button type="primary" size="middle" onClick={() => {
            setShowAddTaskModalVisiable(true)
        }}>
            新增
        </Button>,
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />
    ]

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: "20%",
            fixed: 'left',
            ellipsis: {
                showTitle: true
            },
            sorter: (a, b) => a.name.localeCompare(b.name),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: "10%",
            sorter: (a, b) => a.status - b.status,
            render: (text, record) => <TaskStatus status={record.status}></TaskStatus>
        },
        {
            title: '所属项目',
            dataIndex: 'projectItemId',
            key: 'projectItemId',
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => <>{record.projectItem && `${TASK_TYPE[record.projectItemType]?.name}/${record.projectItem.name}`} </>
        },
        {
            title: '负责人',
            dataIndex: 'userId',
            key: 'userId',
            width: "14%",
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '排期',
            dataIndex: 'date',
            key: 'date',
            width: "20%",
            render: (text, record) => record.actualStartDate ? (`${formetDate(record.actualStartDate)}~${formetDate(record.actualEndDate)}`)
                : (`${formetDate(record.planStartDate)}~${formetDate(record.planStartDate)}`),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: "18%",
            sorter: (a, b) => a.createTime.localeCompare(b.createTime),
            defaultSortOrder: 'descend',
            render: (text, record) => formetTime_MDHm(record.createTime)
        }
    ]

    const filterColumn = (tableColumns) => {
        let showColumns
        if (!showItemColumn) {
            showColumns = tableColumns.filter(column => column.key !== 'projectItemId')
        } else {
            showColumns = tableColumns;
        }
        return showColumns
    }
    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={taskPageLoading}
                    dataSource={taskPage && taskPage.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: taskPage && taskPage.count,
                        current: taskPage && taskPage.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showTaskDetail(record)
                            }
                        }
                    }}
                >
                </Table>
            }
        />
        <TaskAddModal
            visible={showAddTaskModalVisiable}
            projectId={projectId}
            onCancel={() => {
                setShowAddTaskModalVisiable(false)
            }}
            onSaveSuccess={() => {
                saveTask(false)
            }}
        />
    </>
}


export default connect(({ }) => ({
}))(TaskPage);